package org.stephen.recommend.model;

import com.baomidou.mybatisplus.extension.activerecord.Model;
import org.stephen.recommend.util.CommonUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ClassName: RecommendedArticle
 * Description:
 * Date: 2020/12/16 14:23
 *
 * @author stephen.qiu
 */
public class RecommendedArticles extends Model<RecommendedArticles> {
    private static final long serialVersionUID = 1L;

    private HashMap<String, LocalDateTime> recommendedArticleTimeMap;

    public RecommendedArticles() {
        setRecommendedArticleTimeMap(new HashMap<>(CommonUtils.initHashMapSize(0)));
    }

    public HashMap<String, LocalDateTime> getRecommendedArticleTimeMap() {
        return recommendedArticleTimeMap;
    }

    public void setRecommendedArticleTimeMap(HashMap<String, LocalDateTime> recommendedArticleTimeMap) {
        this.recommendedArticleTimeMap = recommendedArticleTimeMap;
    }

    /**
     * 获取beforeDays内推荐过的文章
     *
     * @param beforeDays
     * @return
     */
    public List<String> getRecommendedArticlesList(int beforeDays) {
        List<Map.Entry<String, LocalDateTime>> list = new ArrayList<>(recommendedArticleTimeMap.entrySet());
        return list.stream().filter(c -> c.getValue().isAfter(LocalDateTime.now().plusDays(0 - beforeDays))).map(c -> c.getKey()).collect(Collectors.toList());
    }

    /**
     * 移除previousDays 之外推荐过的文章
     *
     * @param previousDays
     */
    public void updateRecommendedArticles(int previousDays) {
        Iterator<Map.Entry<String, LocalDateTime>> iterator = recommendedArticleTimeMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, LocalDateTime> entry = iterator.next();
            if (entry.getValue().isBefore(LocalDateTime.now().plusDays(0 - previousDays))) {
                iterator.remove();
            }
        }
    }

    /**
     * 更新推荐列表，返回新添加数量
     *
     * @param articleIds
     * @return
     */
    public void updateRecommendedArticles(List<String> articleIds) {
        for (String articleId : articleIds) {
            recommendedArticleTimeMap.put(articleId, LocalDateTime.now());
        }
    }
}
